package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.MemberCompanyManager;
import com.anne.fish.model.MemberCompany;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class MemberCompanyAction extends BaseAction implements Preparable {
    private MemberCompanyManager memberCompanyManager;
    private List memberCompanies;
    private MemberCompany memberCompany;
    private Long id;
    private String query;

    public void setMemberCompanyManager(MemberCompanyManager memberCompanyManager) {
        this.memberCompanyManager = memberCompanyManager;
    }

    public List getMemberCompanies() {
        return memberCompanies;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String memberCompanyId = getRequest().getParameter("memberCompany.id");
            if (memberCompanyId != null && !memberCompanyId.equals("")) {
                memberCompany = memberCompanyManager.get(new Long(memberCompanyId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        memberCompanies = memberCompanyManager.search(query, MemberCompany.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public MemberCompany getMemberCompany() {
        return memberCompany;
    }

    public void setMemberCompany(MemberCompany memberCompany) {
        this.memberCompany = memberCompany;
    }

    public String delete() {
        memberCompanyManager.remove(memberCompany.getId());
        saveMessage(getText("memberCompany.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            memberCompany = memberCompanyManager.get(id);
        } else {
            memberCompany = new MemberCompany();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (memberCompany.getId() == null);

        memberCompanyManager.save(memberCompany);

        String key = (isNew) ? "memberCompany.added" : "memberCompany.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}